from flask import request, jsonify
from flask_jwt_extended import jwt_required
import datetime
from bson import ObjectId
from pymongo import ASCENDING, DESCENDING

from app.api.v1 import api_bp
from app import mongo
from app.utils.auth import permission_required

@api_bp.route('/statistics/patients', methods=['GET'])
@jwt_required()
@permission_required('report:read')
def get_patient_statistics():
    """获取患者统计数据"""
    # 获取查询参数
    start_date = request.args.get('startDate')
    end_date = request.args.get('endDate')
    group_by = request.args.get('groupBy', 'month')  # 默认按月分组
    
    # 处理日期范围
    query = {}
    if start_date:
        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            query['createdAt'] = {'$gte': start_date}
        except ValueError:
            return jsonify({
                'success': False,
                'message': '开始日期格式错误，应为YYYY-MM-DD'
            }), 400
    
    if end_date:
        try:
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            end_date = end_date.replace(hour=23, minute=59, second=59)
            if 'createdAt' in query:
                query['createdAt']['$lte'] = end_date
            else:
                query['createdAt'] = {'$lte': end_date}
        except ValueError:
            return jsonify({
                'success': False,
                'message': '结束日期格式错误，应为YYYY-MM-DD'
            }), 400
    
    # 按照不同维度分组统计
    group_stage = None
    
    if group_by == 'day':
        group_stage = {
            '$group': {
                '_id': {
                    'year': {'$year': '$createdAt'},
                    'month': {'$month': '$createdAt'},
                    'day': {'$dayOfMonth': '$createdAt'}
                },
                'count': {'$sum': 1}
            }
        }
    elif group_by == 'month':
        group_stage = {
            '$group': {
                '_id': {
                    'year': {'$year': '$createdAt'},
                    'month': {'$month': '$createdAt'}
                },
                'count': {'$sum': 1}
            }
        }
    elif group_by == 'year':
        group_stage = {
            '$group': {
                '_id': {'year': {'$year': '$createdAt'}},
                'count': {'$sum': 1}
            }
        }
    elif group_by == 'gender':
        group_stage = {
            '$group': {
                '_id': '$gender',
                'count': {'$sum': 1}
            }
        }
    else:
        return jsonify({
            'success': False,
            'message': '不支持的分组方式'
        }), 400
    
    # 构建聚合管道
    pipeline = [
        {'$match': query},
        group_stage,
        {'$sort': {'_id': 1}}
    ]
    
    # 执行聚合查询
    result = list(mongo.db.patients.aggregate(pipeline))
    
    # 格式化结果
    statistics = []
    
    if group_by == 'day':
        for item in result:
            date_str = f"{item['_id']['year']}-{item['_id']['month']:02d}-{item['_id']['day']:02d}"
            statistics.append({
                'date': date_str,
                'count': item['count']
            })
    elif group_by == 'month':
        for item in result:
            date_str = f"{item['_id']['year']}-{item['_id']['month']:02d}"
            statistics.append({
                'date': date_str,
                'count': item['count']
            })
    elif group_by == 'year':
        for item in result:
            statistics.append({
                'date': str(item['_id']['year']),
                'count': item['count']
            })
    elif group_by == 'gender':
        for item in result:
            statistics.append({
                'gender': item['_id'] or '未知',
                'count': item['count']
            })
    
    # 统计总数
    total_count = mongo.db.patients.count_documents(query)
    
    return jsonify({
        'success': True,
        'data': {
            'total': total_count,
            'groupBy': group_by,
            'statistics': statistics
        }
    }), 200

@api_bp.route('/statistics/prescriptions', methods=['GET'])
@jwt_required()
@permission_required('report:read')
def get_prescription_statistics():
    """获取处方统计数据"""
    # 获取查询参数
    start_date = request.args.get('startDate')
    end_date = request.args.get('endDate')
    group_by = request.args.get('groupBy', 'month')  # 默认按月分组
    
    # 处理日期范围
    query = {}
    if start_date:
        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            query['createdAt'] = {'$gte': start_date}
        except ValueError:
            return jsonify({
                'success': False,
                'message': '开始日期格式错误，应为YYYY-MM-DD'
            }), 400
    
    if end_date:
        try:
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            end_date = end_date.replace(hour=23, minute=59, second=59)
            if 'createdAt' in query:
                query['createdAt']['$lte'] = end_date
            else:
                query['createdAt'] = {'$lte': end_date}
        except ValueError:
            return jsonify({
                'success': False,
                'message': '结束日期格式错误，应为YYYY-MM-DD'
            }), 400
    
    # 按照不同维度分组统计
    group_stage = None
    
    if group_by == 'day':
        group_stage = {
            '$group': {
                '_id': {
                    'year': {'$year': '$createdAt'},
                    'month': {'$month': '$createdAt'},
                    'day': {'$dayOfMonth': '$createdAt'}
                },
                'count': {'$sum': 1},
                'totalCost': {'$sum': '$totalCost'}
            }
        }
    elif group_by == 'month':
        group_stage = {
            '$group': {
                '_id': {
                    'year': {'$year': '$createdAt'},
                    'month': {'$month': '$createdAt'}
                },
                'count': {'$sum': 1},
                'totalCost': {'$sum': '$totalCost'}
            }
        }
    elif group_by == 'year':
        group_stage = {
            '$group': {
                '_id': {'year': {'$year': '$createdAt'}},
                'count': {'$sum': 1},
                'totalCost': {'$sum': '$totalCost'}
            }
        }
    elif group_by == 'status':
        group_stage = {
            '$group': {
                '_id': '$status',
                'count': {'$sum': 1},
                'totalCost': {'$sum': '$totalCost'}
            }
        }
    elif group_by == 'doctor':
        group_stage = {
            '$group': {
                '_id': '$doctorId',
                'count': {'$sum': 1},
                'totalCost': {'$sum': '$totalCost'}
            }
        }
    elif group_by == 'department':
        group_stage = {
            '$group': {
                '_id': '$departmentId',
                'count': {'$sum': 1},
                'totalCost': {'$sum': '$totalCost'}
            }
        }
    else:
        return jsonify({
            'success': False,
            'message': '不支持的分组方式'
        }), 400
    
    # 构建聚合管道
    pipeline = [
        {'$match': query},
        group_stage,
        {'$sort': {'_id': 1}}
    ]
    
    # 执行聚合查询
    result = list(mongo.db.prescriptions.aggregate(pipeline))
    
    # 格式化结果
    statistics = []
    
    if group_by == 'day':
        for item in result:
            date_str = f"{item['_id']['year']}-{item['_id']['month']:02d}-{item['_id']['day']:02d}"
            statistics.append({
                'date': date_str,
                'count': item['count'],
                'totalCost': item['totalCost']
            })
    elif group_by == 'month':
        for item in result:
            date_str = f"{item['_id']['year']}-{item['_id']['month']:02d}"
            statistics.append({
                'date': date_str,
                'count': item['count'],
                'totalCost': item['totalCost']
            })
    elif group_by == 'year':
        for item in result:
            statistics.append({
                'date': str(item['_id']['year']),
                'count': item['count'],
                'totalCost': item['totalCost']
            })
    elif group_by == 'status':
        for item in result:
            statistics.append({
                'status': item['_id'],
                'count': item['count'],
                'totalCost': item['totalCost']
            })
    elif group_by == 'doctor':
        for item in result:
            doctor_id = item['_id']
            doctor_name = '未知'
            if doctor_id and ObjectId.is_valid(doctor_id):
                doctor = mongo.db.doctors.find_one({'_id': ObjectId(doctor_id)})
                if doctor:
                    doctor_name = doctor.get('name', '未知')
            
            statistics.append({
                'doctorId': doctor_id,
                'doctorName': doctor_name,
                'count': item['count'],
                'totalCost': item['totalCost']
            })
    elif group_by == 'department':
        for item in result:
            dept_id = item['_id']
            dept_name = '未知'
            if dept_id and ObjectId.is_valid(dept_id):
                dept = mongo.db.departments.find_one({'_id': ObjectId(dept_id)})
                if dept:
                    dept_name = dept.get('name', '未知')
            
            statistics.append({
                'departmentId': dept_id,
                'departmentName': dept_name,
                'count': item['count'],
                'totalCost': item['totalCost']
            })
    
    # 统计总数和总金额
    total_result = mongo.db.prescriptions.aggregate([
        {'$match': query},
        {'$group': {
            '_id': None,
            'count': {'$sum': 1},
            'totalCost': {'$sum': '$totalCost'}
        }}
    ])
    
    total_list = list(total_result)
    total_count = total_list[0]['count'] if total_list else 0
    total_cost = total_list[0]['totalCost'] if total_list else 0
    
    return jsonify({
        'success': True,
        'data': {
            'total': {
                'count': total_count,
                'cost': total_cost
            },
            'groupBy': group_by,
            'statistics': statistics
        }
    }), 200

@api_bp.route('/statistics/drugs', methods=['GET'])
@jwt_required()
@permission_required('report:read')
def get_drug_statistics():
    """获取药品统计数据"""
    # 获取查询参数
    start_date = request.args.get('startDate')
    end_date = request.args.get('endDate')
    category = request.args.get('category')
    
    # 构建处方查询条件
    prescription_query = {}
    
    # 处理日期范围
    if start_date:
        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            prescription_query['createdAt'] = {'$gte': start_date}
        except ValueError:
            return jsonify({
                'success': False,
                'message': '开始日期格式错误，应为YYYY-MM-DD'
            }), 400
    
    if end_date:
        try:
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            end_date = end_date.replace(hour=23, minute=59, second=59)
            if 'createdAt' in prescription_query:
                prescription_query['createdAt']['$lte'] = end_date
            else:
                prescription_query['createdAt'] = {'$lte': end_date}
        except ValueError:
            return jsonify({
                'success': False,
                'message': '结束日期格式错误，应为YYYY-MM-DD'
            }), 400
    
    # 构建药品查询条件
    drug_query = {}
    if category:
        drug_query['category'] = category
    
    # 获取处方中使用的药品统计
    # 这里需要使用聚合管道来处理处方中的药品项目
    pipeline = [
        {'$match': prescription_query},
        {'$unwind': '$items'},  # 展开items数组
        {'$group': {
            '_id': '$items.drugId',
            'drugName': {'$first': '$items.name'},
            'totalQuantity': {'$sum': '$items.quantity'},
            'totalAmount': {'$sum': '$items.amount'},
            'prescription_count': {'$sum': 1}
        }},
        {'$sort': {'totalQuantity': -1}}
    ]
    
    drug_usage = list(mongo.db.prescriptions.aggregate(pipeline))
    
    # 查询每种药品的完整信息
    detailed_statistics = []
    
    for drug in drug_usage:
        drug_id = drug['_id']
        drug_info = None
        
        if drug_id and ObjectId.is_valid(drug_id):
            drug_info = mongo.db.drugs.find_one({
                '_id': ObjectId(drug_id),
                **drug_query
            })
        
        if drug_info:
            detailed_statistics.append({
                'drugId': str(drug_id),
                'drugName': drug['drugName'],
                'drugCode': drug_info.get('drugCode', ''),
                'category': drug_info.get('category', ''),
                'manufacturer': drug_info.get('manufacturer', ''),
                'specification': drug_info.get('specification', ''),
                'totalQuantity': drug['totalQuantity'],
                'totalAmount': drug['totalAmount'],
                'prescriptionCount': drug['prescription_count']
            })
    
    # 统计总体信息
    total_result = {
        'totalDrugTypes': len(detailed_statistics),
        'totalQuantity': sum(drug['totalQuantity'] for drug in drug_usage),
        'totalAmount': sum(drug['totalAmount'] for drug in drug_usage)
    }
    
    # 查询所有药品分类情况
    if category:
        category_filter = {'category': category}
    else:
        category_filter = {}
    
    category_pipeline = [
        {'$match': category_filter},
        {'$group': {
            '_id': '$category',
            'count': {'$sum': 1}
        }},
        {'$sort': {'count': -1}}
    ]
    
    categories = list(mongo.db.drugs.aggregate(category_pipeline))
    category_stats = [{'category': item['_id'] or '未分类', 'count': item['count']} for item in categories]
    
    return jsonify({
        'success': True,
        'data': {
            'total': total_result,
            'categoryStats': category_stats,
            'drugs': detailed_statistics
        }
    }), 200

@api_bp.route('/statistics/visits', methods=['GET'])
@jwt_required()
@permission_required('report:read')
def get_visit_statistics():
    """获取就诊统计数据"""
    try:
        # 获取查询参数
        start_date = request.args.get('startDate')
        end_date = request.args.get('endDate')
        group_by = request.args.get('groupBy', 'month')  # 默认按月分组
        department_id = request.args.get('departmentId')
        
        # 处理日期范围
        query = {}
        if start_date:
            try:
                start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
                query['appointmentDate'] = {'$gte': start_date}
            except ValueError:
                return jsonify({
                    'success': False,
                    'message': '开始日期格式错误，应为YYYY-MM-DD'
                }), 400
        
        if end_date:
            try:
                end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
                end_date = end_date.replace(hour=23, minute=59, second=59)
                if 'appointmentDate' in query:
                    query['appointmentDate']['$lte'] = end_date
                else:
                    query['appointmentDate'] = {'$lte': end_date}
            except ValueError:
                return jsonify({
                    'success': False,
                    'message': '结束日期格式错误，应为YYYY-MM-DD'
                }), 400
        
        # 按科室筛选
        if department_id:
            query['departmentId'] = department_id
        
        # 按预约状态筛选（如果提供）
        status = request.args.get('status')
        if status and status != 'all':
            query['status'] = status
        
        # 按照不同维度分组统计
        group_stage = None
        
        if group_by == 'day':
            group_stage = {
                '$group': {
                    '_id': {
                        'year': {'$year': '$appointmentDate'},
                        'month': {'$month': '$appointmentDate'},
                        'day': {'$dayOfMonth': '$appointmentDate'}
                    },
                    'count': {'$sum': 1},
                    'departments': {'$addToSet': '$departmentId'}
                }
            }
        elif group_by == 'month':
            group_stage = {
                '$group': {
                    '_id': {
                        'year': {'$year': '$appointmentDate'},
                        'month': {'$month': '$appointmentDate'}
                    },
                    'count': {'$sum': 1},
                    'departments': {'$addToSet': '$departmentId'}
                }
            }
        elif group_by == 'year':
            group_stage = {
                '$group': {
                    '_id': {'year': {'$year': '$appointmentDate'}},
                    'count': {'$sum': 1},
                    'departments': {'$addToSet': '$departmentId'}
                }
            }
        elif group_by == 'department':
            group_stage = {
                '$group': {
                    '_id': '$departmentId',
                    'count': {'$sum': 1}
                }
            }
        elif group_by == 'status':
            group_stage = {
                '$group': {
                    '_id': '$status',
                    'count': {'$sum': 1}
                }
            }
        else:
            return jsonify({
                'success': False,
                'message': '不支持的分组方式'
            }), 400
        
        # 构建聚合管道
        pipeline = [
            {'$match': query},
            group_stage,
            {'$sort': {'_id': 1}}
        ]
        
        # 执行聚合查询
        result = list(mongo.db.appointments.aggregate(pipeline))
        
        # 格式化结果
        statistics = []
        
        if group_by == 'day':
            for item in result:
                try:
                    if not item.get('_id'):
                        continue
                    
                    year = item['_id'].get('year')
                    month = item['_id'].get('month')
                    day = item['_id'].get('day')
                    
                    if year is None or month is None or day is None:
                        continue
                    
                    # 安全格式化日期字符串
                    date_str = f"{year}-{int(month):02d}-{int(day):02d}"
                    
                    # 计算部门数量
                    departments = item.get('departments', [])
                    dept_count = len([d for d in departments if d is not None]) if departments else 0
                    
                    statistics.append({
                        'date': date_str,
                        'count': item.get('count', 0),
                        'departmentCount': dept_count
                    })
                except Exception as e:
                    print(f"处理日统计项时出错: {str(e)}")
                    continue
                    
        elif group_by == 'month':
            for item in result:
                try:
                    if not item.get('_id'):
                        continue
                    
                    year = item['_id'].get('year')
                    month = item['_id'].get('month')
                    
                    if year is None or month is None:
                        continue
                    
                    # 安全格式化日期字符串
                    date_str = f"{year}-{int(month):02d}"
                    
                    # 计算部门数量
                    departments = item.get('departments', [])
                    dept_count = len([d for d in departments if d is not None]) if departments else 0
                    
                    statistics.append({
                        'date': date_str,
                        'count': item.get('count', 0),
                        'departmentCount': dept_count
                    })
                except Exception as e:
                    print(f"处理月统计项时出错: {str(e)}")
                    continue
                    
        elif group_by == 'year':
            for item in result:
                try:
                    if not item.get('_id'):
                        continue
                    
                    year = item['_id'].get('year')
                    
                    if year is None:
                        continue
                    
                    # 计算部门数量
                    departments = item.get('departments', [])
                    dept_count = len([d for d in departments if d is not None]) if departments else 0
                    
                    statistics.append({
                        'date': str(year),
                        'count': item.get('count', 0),
                        'departmentCount': dept_count
                    })
                except Exception as e:
                    print(f"处理年统计项时出错: {str(e)}")
                    continue
                    
        elif group_by == 'department':
            for item in result:
                try:
                    dept_id = item.get('_id')
                    dept_name = '未知'
                    
                    if dept_id and ObjectId.is_valid(dept_id):
                        dept = mongo.db.departments.find_one({'_id': ObjectId(dept_id)})
                        if dept:
                            dept_name = dept.get('name', '未知')
                    
                    statistics.append({
                        'departmentId': dept_id,
                        'departmentName': dept_name,
                        'count': item.get('count', 0)
                    })
                except Exception as e:
                    print(f"处理科室统计项时出错: {str(e)}")
                    continue
                    
        elif group_by == 'status':
            for item in result:
                try:
                    status = item.get('_id')
                    if status is None:
                        status = '未知'
                        
                    statistics.append({
                        'status': status,
                        'count': item.get('count', 0)
                    })
                except Exception as e:
                    print(f"处理状态统计项时出错: {str(e)}")
                    continue
        
        # 统计总数
        total_count = mongo.db.appointments.count_documents(query)
        
        return jsonify({
            'success': True,
            'data': {
                'total': total_count,
                'groupBy': group_by,
                'statistics': statistics
            }
        }), 200
    except Exception as e:
        print(f"就诊统计接口错误: {str(e)}")
        return jsonify({
            'success': False,
            'message': '服务器内部错误',
            'error': str(e)
        }), 500

@api_bp.route('/statistics/departments', methods=['GET'])
@jwt_required()
@permission_required('report:read')
def get_department_statistics():
    """获取科室工作量统计数据"""
    # 获取查询参数
    start_date = request.args.get('startDate')
    end_date = request.args.get('endDate')
    department_id = request.args.get('departmentId')
    
    # 处理日期范围
    query = {}
    if start_date:
        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            query['visitDate'] = {'$gte': start_date}
        except ValueError:
            return jsonify({
                'success': False,
                'message': '开始日期格式错误，应为YYYY-MM-DD'
            }), 400
    
    if end_date:
        try:
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            end_date = end_date.replace(hour=23, minute=59, second=59)
            if 'visitDate' in query:
                query['visitDate']['$lte'] = end_date
            else:
                query['visitDate'] = {'$lte': end_date}
        except ValueError:
            return jsonify({
                'success': False,
                'message': '结束日期格式错误，应为YYYY-MM-DD'
            }), 400
    
    # 按科室筛选
    if department_id:
        query['departmentId'] = department_id
    
    # 按预约状态筛选（如果提供）
    status = request.args.get('status')
    if status and status != 'all':
        query['status'] = status
    
    # 按科室分组统计就诊量
    appointment_pipeline = [
        {'$match': query},
        {'$group': {
            '_id': '$departmentId',
            'appointmentCount': {'$sum': 1}
        }},
        {'$sort': {'appointmentCount': -1}}
    ]
    
    department_appointments = list(mongo.db.appointments.aggregate(appointment_pipeline))
    
    # 配置处方查询条件
    prescription_query = {}
    if start_date:
        prescription_query['createdAt'] = {'$gte': start_date}
    if end_date:
        if 'createdAt' in prescription_query:
            prescription_query['createdAt']['$lte'] = end_date
        else:
            prescription_query['createdAt'] = {'$lte': end_date}
    
    if department_id:
        prescription_query['departmentId'] = department_id
    
    # 按科室分组统计处方数量和金额
    prescription_pipeline = [
        {'$match': prescription_query},
        {'$group': {
            '_id': '$departmentId',
            'prescriptionCount': {'$sum': 1},
            'totalAmount': {'$sum': '$totalAmount'}
        }},
        {'$sort': {'prescriptionCount': -1}}
    ]
    
    department_prescriptions = list(mongo.db.prescriptions.aggregate(prescription_pipeline))
    
    # 整合数据
    department_stats = {}
    
    # 添加就诊数据
    for item in department_appointments:
        dept_id = item['_id']
        if dept_id not in department_stats:
            department_stats[dept_id] = {
                'departmentId': dept_id,
                'appointmentCount': item['appointmentCount'],
                'prescriptionCount': 0,
                'totalAmount': 0
            }
        else:
            department_stats[dept_id]['appointmentCount'] = item['appointmentCount']
    
    # 添加处方数据
    for item in department_prescriptions:
        dept_id = item['_id']
        if dept_id not in department_stats:
            department_stats[dept_id] = {
                'departmentId': dept_id,
                'appointmentCount': 0,
                'prescriptionCount': item['prescriptionCount'],
                'totalAmount': item['totalAmount']
            }
        else:
            department_stats[dept_id]['prescriptionCount'] = item['prescriptionCount']
            department_stats[dept_id]['totalAmount'] = item['totalAmount']
    
    # 获取科室名称
    detailed_stats = []
    
    for dept_id, stats in department_stats.items():
        dept_name = '未知'
        if dept_id and ObjectId.is_valid(dept_id):
            dept = mongo.db.departments.find_one({'_id': ObjectId(dept_id)})
            if dept:
                dept_name = dept.get('name', '未知')
                stats['category'] = dept.get('category', '未知')
        
        stats['departmentName'] = dept_name
        detailed_stats.append(stats)
    
    # 按就诊量排序
    detailed_stats.sort(key=lambda x: x['appointmentCount'], reverse=True)
    
    # 统计总数
    total_result = {
        'totalDepartments': len(detailed_stats),
        'totalAppointments': sum(item['appointmentCount'] for item in detailed_stats),
        'totalPrescriptions': sum(item['prescriptionCount'] for item in detailed_stats),
        'totalAmount': sum(item['totalAmount'] for item in detailed_stats)
    }
    
    return jsonify({
        'success': True,
        'data': {
            'total': total_result,
            'departments': detailed_stats
        }
    }), 200

@api_bp.route('/statistics/doctors', methods=['GET'])
@jwt_required()
@permission_required('report:read')
def get_doctor_statistics():
    """获取医生工作量统计数据"""
    # 获取查询参数
    start_date = request.args.get('startDate')
    end_date = request.args.get('endDate')
    department_id = request.args.get('departmentId')
    doctor_id = request.args.get('doctorId')
    
    # 处理日期范围
    query = {}
    if start_date:
        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            query['visitDate'] = {'$gte': start_date}
        except ValueError:
            return jsonify({
                'success': False,
                'message': '开始日期格式错误，应为YYYY-MM-DD'
            }), 400
    
    if end_date:
        try:
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            end_date = end_date.replace(hour=23, minute=59, second=59)
            if 'visitDate' in query:
                query['visitDate']['$lte'] = end_date
            else:
                query['visitDate'] = {'$lte': end_date}
        except ValueError:
            return jsonify({
                'success': False,
                'message': '结束日期格式错误，应为YYYY-MM-DD'
            }), 400
    
    # 按科室或医生筛选
    if department_id:
        query['departmentId'] = department_id
    
    if doctor_id:
        query['doctorId'] = doctor_id
    
    # 按预约状态筛选（如果提供）
    status = request.args.get('status')
    if status and status != 'all':
        query['status'] = status
    
    # 按医生分组统计就诊量
    appointment_pipeline = [
        {'$match': query},
        {'$group': {
            '_id': '$doctorId',
            'appointmentCount': {'$sum': 1},
            'departmentId': {'$first': '$departmentId'}
        }},
        {'$sort': {'appointmentCount': -1}}
    ]
    
    doctor_appointments = list(mongo.db.appointments.aggregate(appointment_pipeline))
    
    # 配置处方查询条件
    prescription_query = {}
    if start_date:
        prescription_query['createdAt'] = {'$gte': start_date}
    if end_date:
        if 'createdAt' in prescription_query:
            prescription_query['createdAt']['$lte'] = end_date
        else:
            prescription_query['createdAt'] = {'$lte': end_date}
    
    if department_id:
        prescription_query['departmentId'] = department_id
    
    if doctor_id:
        prescription_query['doctorId'] = doctor_id
    
    # 按医生分组统计处方数量和金额
    prescription_pipeline = [
        {'$match': prescription_query},
        {'$group': {
            '_id': '$doctorId',
            'prescriptionCount': {'$sum': 1},
            'totalAmount': {'$sum': '$totalAmount'},
            'departmentId': {'$first': '$departmentId'}
        }},
        {'$sort': {'prescriptionCount': -1}}
    ]
    
    doctor_prescriptions = list(mongo.db.prescriptions.aggregate(prescription_pipeline))
    
    # 配置医疗记录查询条件
    record_query = {}
    if start_date:
        record_query['createdAt'] = {'$gte': start_date}
    if end_date:
        if 'createdAt' in record_query:
            record_query['createdAt']['$lte'] = end_date
        else:
            record_query['createdAt'] = {'$lte': end_date}
    
    if department_id:
        record_query['departmentId'] = department_id
    
    if doctor_id:
        record_query['doctorId'] = doctor_id
    
    # 按医生分组统计医疗记录数量
    record_pipeline = [
        {'$match': record_query},
        {'$group': {
            '_id': '$doctorId',
            'recordCount': {'$sum': 1},
            'departmentId': {'$first': '$departmentId'}
        }},
        {'$sort': {'recordCount': -1}}
    ]
    
    doctor_records = list(mongo.db.medical_records.aggregate(record_pipeline))
    
    # 整合数据
    doctor_stats = {}
    
    # 添加就诊数据
    for item in doctor_appointments:
        doc_id = item['_id']
        if doc_id not in doctor_stats:
            doctor_stats[doc_id] = {
                'doctorId': doc_id,
                'departmentId': item.get('departmentId'),
                'appointmentCount': item['appointmentCount'],
                'prescriptionCount': 0,
                'recordCount': 0,
                'totalAmount': 0
            }
        else:
            doctor_stats[doc_id]['appointmentCount'] = item['appointmentCount']
            if 'departmentId' not in doctor_stats[doc_id] and 'departmentId' in item:
                doctor_stats[doc_id]['departmentId'] = item['departmentId']
    
    # 添加处方数据
    for item in doctor_prescriptions:
        doc_id = item['_id']
        if doc_id not in doctor_stats:
            doctor_stats[doc_id] = {
                'doctorId': doc_id,
                'departmentId': item.get('departmentId'),
                'appointmentCount': 0,
                'prescriptionCount': item['prescriptionCount'],
                'recordCount': 0,
                'totalAmount': item['totalAmount']
            }
        else:
            doctor_stats[doc_id]['prescriptionCount'] = item['prescriptionCount']
            doctor_stats[doc_id]['totalAmount'] = item['totalAmount']
            if 'departmentId' not in doctor_stats[doc_id] and 'departmentId' in item:
                doctor_stats[doc_id]['departmentId'] = item['departmentId']
    
    # 添加医疗记录数据
    for item in doctor_records:
        doc_id = item['_id']
        if doc_id not in doctor_stats:
            doctor_stats[doc_id] = {
                'doctorId': doc_id,
                'departmentId': item.get('departmentId'),
                'appointmentCount': 0,
                'prescriptionCount': 0,
                'recordCount': item['recordCount'],
                'totalAmount': 0
            }
        else:
            doctor_stats[doc_id]['recordCount'] = item['recordCount']
            if 'departmentId' not in doctor_stats[doc_id] and 'departmentId' in item:
                doctor_stats[doc_id]['departmentId'] = item['departmentId']
    
    # 获取医生和科室信息
    detailed_stats = []
    
    for doc_id, stats in doctor_stats.items():
        # 获取医生信息
        doc_name = '未知'
        if doc_id and ObjectId.is_valid(doc_id):
            doctor = mongo.db.doctors.find_one({'_id': ObjectId(doc_id)})
            if doctor:
                doc_name = doctor.get('name', '未知')
                stats['title'] = doctor.get('title', '')
        
        stats['doctorName'] = doc_name
        
        # 获取科室信息
        dept_id = stats.get('departmentId')
        dept_name = '未知'
        if dept_id and ObjectId.is_valid(dept_id):
            dept = mongo.db.departments.find_one({'_id': ObjectId(dept_id)})
            if dept:
                dept_name = dept.get('name', '未知')
        
        stats['departmentName'] = dept_name
        
        # 计算工作效率指标
        total_work = stats['appointmentCount'] + stats['prescriptionCount'] + stats['recordCount']
        if total_work > 0:
            stats['efficiency'] = round(stats['totalAmount'] / total_work, 2)
        else:
            stats['efficiency'] = 0
        
        detailed_stats.append(stats)
    
    # 按就诊量排序
    detailed_stats.sort(key=lambda x: x['appointmentCount'], reverse=True)
    
    # 统计总数
    total_result = {
        'totalDoctors': len(detailed_stats),
        'totalAppointments': sum(item['appointmentCount'] for item in detailed_stats),
        'totalPrescriptions': sum(item['prescriptionCount'] for item in detailed_stats),
        'totalRecords': sum(item['recordCount'] for item in detailed_stats),
        'totalAmount': sum(item['totalAmount'] for item in detailed_stats)
    }
    
    return jsonify({
        'success': True,
        'data': {
            'total': total_result,
            'doctors': detailed_stats
        }
    }), 200

@api_bp.route('/statistics/income', methods=['GET'])
@jwt_required()
@permission_required('report:read')
def get_income_statistics():
    """获取收入统计数据"""
    # 获取查询参数
    start_date = request.args.get('startDate')
    end_date = request.args.get('endDate')
    group_by = request.args.get('groupBy', 'month')  # 默认按月分组
    department_id = request.args.get('departmentId')
    
    # 处理日期范围
    query = {}
    if start_date:
        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            query['createdAt'] = {'$gte': start_date}
        except ValueError:
            return jsonify({
                'success': False,
                'message': '开始日期格式错误，应为YYYY-MM-DD'
            }), 400
    
    if end_date:
        try:
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            end_date = end_date.replace(hour=23, minute=59, second=59)
            if 'createdAt' in query:
                query['createdAt']['$lte'] = end_date
            else:
                query['createdAt'] = {'$lte': end_date}
        except ValueError:
            return jsonify({
                'success': False,
                'message': '结束日期格式错误，应为YYYY-MM-DD'
            }), 400
    
    # 按科室筛选
    if department_id:
        query['departmentId'] = department_id
    
    # 只统计成功支付的记录
    query['status'] = '成功'
    
    # 按照不同维度分组统计
    group_stage = None
    
    if group_by == 'day':
        group_stage = {
            '$group': {
                '_id': {
                    'year': {'$year': '$createdAt'},
                    'month': {'$month': '$createdAt'},
                    'day': {'$dayOfMonth': '$createdAt'}
                },
                'totalAmount': {'$sum': '$totalAmount'},
                'count': {'$sum': 1}
            }
        }
    elif group_by == 'month':
        group_stage = {
            '$group': {
                '_id': {
                    'year': {'$year': '$createdAt'},
                    'month': {'$month': '$createdAt'}
                },
                'totalAmount': {'$sum': '$totalAmount'},
                'count': {'$sum': 1}
            }
        }
    elif group_by == 'year':
        group_stage = {
            '$group': {
                '_id': {'year': {'$year': '$createdAt'}},
                'totalAmount': {'$sum': '$totalAmount'},
                'count': {'$sum': 1}
            }
        }
    elif group_by == 'department':
        group_stage = {
            '$group': {
                '_id': '$departmentId',
                'totalAmount': {'$sum': '$totalAmount'},
                'count': {'$sum': 1}
            }
        }
    elif group_by == 'paymentType':
        group_stage = {
            '$group': {
                '_id': '$paymentType',
                'totalAmount': {'$sum': '$totalAmount'},
                'count': {'$sum': 1}
            }
        }
    else:
        return jsonify({
            'success': False,
            'message': '不支持的分组方式'
        }), 400
    
    # 构建聚合管道
    pipeline = [
        {'$match': query},
        group_stage,
        {'$sort': {'_id': 1}}
    ]
    
    # 执行聚合查询
    result = list(mongo.db.payments.aggregate(pipeline))
    
    # 格式化结果
    statistics = []
    
    if group_by == 'day':
        for item in result:
            date_str = f"{item['_id']['year']}-{item['_id']['month']:02d}-{item['_id']['day']:02d}"
            statistics.append({
                'date': date_str,
                'totalAmount': item['totalAmount'],
                'count': item['count']
            })
    elif group_by == 'month':
        for item in result:
            date_str = f"{item['_id']['year']}-{item['_id']['month']:02d}"
            statistics.append({
                'date': date_str,
                'totalAmount': item['totalAmount'],
                'count': item['count']
            })
    elif group_by == 'year':
        for item in result:
            statistics.append({
                'date': str(item['_id']['year']),
                'totalAmount': item['totalAmount'],
                'count': item['count']
            })
    elif group_by == 'department':
        for item in result:
            dept_id = item['_id']
            dept_name = '未知'
            if dept_id and ObjectId.is_valid(dept_id):
                dept = mongo.db.departments.find_one({'_id': ObjectId(dept_id)})
                if dept:
                    dept_name = dept.get('name', '未知')
            
            statistics.append({
                'departmentId': dept_id,
                'departmentName': dept_name,
                'totalAmount': item['totalAmount'],
                'count': item['count']
            })
    elif group_by == 'paymentType':
        payment_type_map = {
            'cash': '现金',
            'alipay': '支付宝',
            'wechat': '微信',
            'card': '医保卡',
            'insurance': '商业保险'
        }
        
        for item in result:
            payment_type = item['_id']
            payment_type_name = payment_type_map.get(payment_type, payment_type)
            
            statistics.append({
                'paymentType': payment_type,
                'paymentTypeName': payment_type_name,
                'totalAmount': item['totalAmount'],
                'count': item['count']
            })
    
    # 计算总收入
    total_result = mongo.db.payments.aggregate([
        {'$match': query},
        {'$group': {
            '_id': None,
            'totalAmount': {'$sum': '$totalAmount'},
            'count': {'$sum': 1}
        }}
    ])
    
    total_list = list(total_result)
    total_amount = total_list[0]['totalAmount'] if total_list else 0
    total_count = total_list[0]['count'] if total_list else 0
    
    return jsonify({
        'success': True,
        'data': {
            'total': {
                'amount': total_amount,
                'count': total_count
            },
            'groupBy': group_by,
            'statistics': statistics
        }
    }), 200 